package com.sinodata.bsm.cicp.collector.apache;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.CollectorUtil;
import com.sinodata.bsm.common.vo.ResPropertyValue;

/**
 * 
 * <p>
 * Description:采集告警日志文件中的内容 
 * </p>
 *
 * @author liulibo
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-12-20 15:29:33      liulibo        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public class BasicStatusCollector extends Collector {

    private static final Logger logger = Logger.getLogger(BasicStatusCollector.class);

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        String url = this.getParamMap().get("URLAddress").trim();
        List<ResPropertyValue> retList = new ArrayList<ResPropertyValue>();
        String[] propMetas = getPropMeta();
        ResPropertyValue propertyValueX = new ResPropertyValue();
        ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];
        Pattern patt = java.util.regex.Pattern.compile("/.*>");
        Matcher match;
        String url1 = null;
        if (url.endsWith("/")) {
            url1 = url + "server-status";
        } else {
            url1 = url + "/server-status";
        }

        String respXml;

        try {
            respXml = CollectorUtil.getHttpXml(url1);
        } catch (Exception e) {
            logger.error("failed to collect apache basic status", e);
            throw new CollectorException(e);
        }

        patt = java.util.regex.Pattern.compile("Server Version:([^<]*).*>");
        match = patt.matcher(respXml);
        if (match.find()) {
            propValues[0] = ResPropertyValue.createPropValue(match.group(1), propMetas[0]);
        }
        patt = java.util.regex.Pattern.compile("Restart Time:.*[,，]\\s*(.*\\d\\s+).*");
        match = patt.matcher(respXml);
        if (match.find()) {
            propValues[1] = ResPropertyValue.createPropValue(match.group(1).trim(), propMetas[1]);
        }
        propertyValueX.setValues(propValues);
        retList.add(propertyValueX);

        return retList;
    }

    @Override
    public String[] getParamMeta() {
        return new String[] { "URLAddress" };
    }

    @Override
    public String[] getPropMeta() {
        //        return new String[] { "ApacheVersion", "Runtime" };
        return new String[] { "$1", "$2" };

    }

}